﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using xjjxmm.infrastructure.Common;
using XjjXmm.Infrastructure.Configuration;
using XjjXmm.Infrastructure.Constant;

namespace xjjxmm.infrastructure.compont;

public class SwaggerCompont : ICompont
{
    public int Order { get; set; } = 500;

    public bool Regist(WebApplicationBuilder builder) {
        builder.Services.AddSwaggerGen(c =>
        {
            var frameConfig = ConfigHelper.GetSection<FrameworkConfig>(CommonConstant.FrameworkConfigKey);
            c.SwaggerDoc(frameConfig!.SwaggerName, new OpenApiInfo
            {
                Title = "Swagger接口文档",
                Version = "v1",
                Description = $"XjjXmm.WebApi HTTP API V1",

            });

            // 获取xml注释文件的目录
            var xmlPath = Path.Combine(AppContext.BaseDirectory, "web.xml");
            c.IncludeXmlComments(xmlPath, true);//默认的第二个参数是false，这个是controller的注释，记得修改

            //放置接口Auth授权按钮
            c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme()
            {
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                Description = "Bearer Token",
                Name = "Authorization",
                BearerFormat = "JWT",
                Scheme = JwtBearerDefaults.AuthenticationScheme
            });

            //添加Jwt验证设置,添加请求头信息
            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    new string[] { }
                }
            });
        });

        return false;
    }

    public bool Use(WebApplication app)
    {
        var frameConfig = ConfigHelper.GetSection<FrameworkConfig>(CommonConstant.FrameworkConfigKey);

        //  var options = new RewriteOptions()
        // .AddRewrite("^swagger(.*)", "admin/swagger$1", skipRemainingRules: true);

        // app.UseRewriter(options);

        var endPoint = $"/swagger/{frameConfig!.SwaggerName}/swagger.json";
        var route = "swagger";
        if (!string.IsNullOrEmpty(frameConfig?.Prefix))
        {
            //endPoint = "/" + frameConfig?.prefix + endPoint;
            route = frameConfig?.Prefix + "/" + route;
        }

        //
        app.UseSwaggerUI(c =>
        {
            c.RoutePrefix = route;

            c.SwaggerEndpoint(endPoint, "XjjXmm");
        });

        // app.UsePathBase("/api1"); // 设置路由前缀

        app.UseSwagger();

        return true;
    }
}
